<template>
  <Modal v-model="visible" width="800" title="回款信息">
    <Tabs v-model="curTab" @on-click="onClickTabs" type="card" :animated="false">
      <TabPane name="writeoff" label="核销信息">
        <div class="count">
          <p>累计核销金额：{{ $dt.tool.formatterMoney(writeoffAmount) }} 元</p>
          <p>剩余应结佣金：{{ $dt.tool.formatterMoney(surplusAmount) }} 元</p>
        </div>
        <dt-grid
          ref="writeoffTable"
          border
          :columns="writeoffColumns"
          :list="writeoffList"
          :height-resize="true"
          :row-style="({ row }) => (!row.isValid ? { backgroundColor: '#F4F4F4' } : {})" />
      </TabPane>
      <TabPane name="invoice" label="开票信息">
        <div class="count">
          <p>
            累计开票金额：{{ invoiceInfo.hasAmount ? $dt.tool.formatterMoney(invoiceInfo.hasAmount) : 0 }}元
          </p>
          <p>
            未税金额：{{ invoiceInfo.noTaxAmount ? $dt.tool.formatterMoney(invoiceInfo.noTaxAmount) : 0 }}元
          </p>
          <p>
            未开票金额：{{
              invoiceInfo.notYetAmount ? $dt.tool.formatterMoney(invoiceInfo.notYetAmount) : 0
            }}元
          </p>
          <p>
            发票回执：
            <span v-if="invoiceInfo.isInvoiceDelayUpload">
              延期{{ $dt.dictInfo().__value('delayTime', invoiceInfo.delayTime) }}
            </span>
            <template v-else-if="invoiceInfo.invoiceReceiptAttaches?.length > 0">
              <a
                v-for="(item, idx) in invoiceInfo.invoiceReceiptAttaches"
                :key="idx"
                @click="onFile(item)"
                style="margin-left: 8px">
                {{ item.fileName }}
              </a>
            </template>
            <span v-else>-</span>
          </p>
        </div>
        <dt-grid
          ref="invoiceTable"
          border
          :columns="invoiceColumns"
          :list="invoiceList"
          :height-resize="true"
          :row-style="({ row }) => (row.delFlag ? { backgroundColor: '#F4F4F4' } : {})" />
      </TabPane>
      <TabPane name="confirm" label="确认信息">
        <Form ref="confirmForm" :model="confirmForm" :label-width="120">
          <FormItem label="附件类型:">
            <template v-if="confirmForm.voucherAttachType">
              {{ $dt.dictInfo().__value('voucherAttachType', confirmForm.voucherAttachType) }}
            </template>
            <template v-else>--</template>
          </FormItem>
          <FormItem v-if="confirmForm.voucherAttachType != 7" label="确认日期:">
            {{ confirmForm.confirmDate || '--' }}
          </FormItem>
          <FormItem v-if="confirmForm.voucherAttachType != 7" label="凭证确认金额:">
            <template v-if="confirmForm.voucherConfirmAmount">
              {{ confirmForm.voucherConfirmAmount }} 元
            </template>
            <template v-else>--</template>
          </FormItem>
          <FormItem v-if="confirmForm.voucherAttachType == 7" label="延期时间:">
            <template v-if="confirmForm.delayTime">
              {{ $dt.dictInfo().__value('delayTime', confirmForm.delayTime) }}
            </template>
            <template v-else>--</template>
          </FormItem>
          <FormItem
            v-if="confirmForm.voucherAttachType != '6' && confirmForm.voucherAttachType != '7'"
            label="凭证:">
            <Button
              v-if="confirmForm.voucherAttach && confirmForm.voucherAttach.length && unlocking('0210020603')"
              icon="ios-download-outline"
              type="primary"
              @click="onDownload">
              下载
            </Button>
          </FormItem>
          <FormItem
            v-if="confirmForm.voucherAttachType == '6' || confirmForm.voucherAttachType == '7'"
            label="备注:">
            {{ confirmForm.voucherRemark || '--' }}
          </FormItem>
        </Form>
      </TabPane>
      <TabPane name="company" label="入账公司">
        <div class="count">
          <p style="margin: 20px 40px">入账公司：{{ accountingCompany ?? '-' }}</p>
        </div>
      </TabPane>
    </Tabs>

    <preview-image ref="preViewImage" :images="images" :showDownLoad="true" :showIndex="showIndex" />

    <div slot="footer">
      <Button v-if="curTab == 'company' || curTab == 'confirm'" @click="onEdit" type="primary">编辑</Button>
      <Button v-if="curTab == 'invoice'" @click="onEdit" type="primary">编辑回执</Button>
      <Button @click="hide">关闭</Button>
    </div>

    <company-modal ref="company" @success="onSuccess" />
    <confirm-modal ref="confirm" @success="onSuccess" />
    <invoice-receipt-modal ref="invoiceReceipt" @success="onSuccess" />
  </Modal>
</template>

<script>
  import columnOpt from '../opt/writeoffColumn.js'
  import toolMgr from '@/biz/base/tool.js'
  import calcFun from '../opt/calc.js'
  import informationMgr from '@/biz/commission/information.js'
  import companyModal from './company-modal.vue'
  import confirmModal from './confirm-modal.vue'
  import invoiceReceiptModal from './invoice-receipt-modal.vue'

  export default {
    components: {
      companyModal,
      confirmModal,
      invoiceReceiptModal
    },
    props: {
      data: Object
    },
    data() {
      return {
        visible: false,
        curTab: 'writeoff',
        writeoffColumns: [],
        writeoffList: [],
        invoiceColumns: [],
        invoiceList: [],
        invoiceInfo: {},
        confirmForm: {
          confirmDate: ''
        },
        accountingCompany: null,
        info: {},
        writeoffAmount: 0,
        surplusAmount: 0,
        images: [],
        showIndex: 0
      }
    },
    methods: {
      // 作废
      onCancellation({ row, rowIndex }) {
        if (this.curTab === 'writeoff') {
          let data = this.writeoffList.filter((i) => !i.bonusName && i.isValid)
          let lastIndex = this.writeoffList.findIndex(
            (i) => i.writeOffId === data[data.length - 1].writeOffId
          )
          if (rowIndex < lastIndex) {
            this.$Message.error('请按核销单时间倒序进行作废操作')
            return
          }
          this.$Modal.confirm({
            title: '是否废弃该条核销数据？',
            onOk: () => {
              informationMgr.cancelWriteOff(row.writeOffId).then((res) => {
                this.$Message.success('操作成功')
                this.writeoffAmount = calcFun.dealPrecision(
                  Number(this.writeoffAmount) - Number(row.writeOffAmount)
                )
                this.surplusAmount = calcFun.dealPrecision(
                  Number(this.surplusAmount) + Number(row.writeOffAmount)
                )
                this.writeoffInfo()
                this.$emit('success')
              })
            }
          })
        } else if (this.curTab === 'invoice') {
          this.$Modal.confirm({
            title: '是否废弃该条开票数据？',
            onOk: () => {
              informationMgr.cancelInvoicing(row.invoicingId).then((res) => {
                this.$Message.success('操作成功')
                this.invoicingInfo()
                this.$emit('success')
              })
            }
          })
        }
      },
      // 查看发票凭证
      onDetail(row) {
        let invoiceVoucher = row.invoiceVoucher.split(',')
        this.images = invoiceVoucher.filter((i) => i.indexOf('.pdf') < 0)
        this.showIndex = 0
        this.$refs.preViewImage.show()

        let pdfs = invoiceVoucher.filter((i) => i.indexOf('.pdf') > 0)
        for (let item of pdfs) {
          window.open(item)
        }
      },
      // 下载双方盖章凭证
      onDownload(data) {
        toolMgr.downloadCenter(
          '/dt-order/commission/downLoadVoucher',
          {
            commissionId: this.info.commissionId
          },
          'get'
        )
      },
      onClickTabs() {
        switch (this.curTab) {
          case 'writeoff':
            this.writeoffColumns = columnOpt.writeoffHeaders(this)
            this.writeoffInfo()
            break
          case 'invoice':
            this.invoiceColumns = columnOpt.invoiceHeaders(this)
            this.invoicingInfo()
            break
          case 'confirm':
            this.confirmInfo()
            break
        }
      },
      // 获取核销列表信息
      writeoffInfo() {
        informationMgr.writeoffInfo(this.info.commissionId).then((res) => {
          this.writeoffList = res
        })
      },
      // 获取开票列表信息
      invoicingInfo() {
        informationMgr.invoicingInfo(this.info.commissionId).then((res) => {
          this.invoiceList = res.orInvoicingList
          this.invoiceInfo = res
        })
      },
      // 获取确认信息
      confirmInfo() {
        informationMgr.getVoucher(this.info.commissionId).then((res) => {
          this.confirmForm = res
        })
      },
      show(info) {
        this.visible = true
        this.curTab = 'writeoff'
        this.writeoffColumns = columnOpt.writeoffHeaders(this)
        this.info = info
        this.accountingCompany = info.accountingCompany
        this.writeoffAmount = info.writtenOffAmount
        this.surplusAmount = info.preCommissionAmount - info.writtenOffAmount
        this.writeoffInfo()
      },
      hide() {
        this.visible = false
      },
      // 修改入账公司
      onEdit() {
        if (this.curTab == 'company') {
          this.$refs.company.show(this.info)
        } else if (this.curTab == 'confirm') {
          this.$refs.confirm.show(this.info)
        } else if (this.curTab == 'invoice') {
          this.$refs.invoiceReceipt.show({ ...this.info, ...this.invoiceInfo })
        }
      },
      onSuccess(name) {
        console.log(name)
        this.accountingCompany = name
        this.onClickTabs()
        this.$emit('success')
      },
      onFile(item) {
        toolMgr.downloadFile(item.attachAddress, item.fileName)
      }
    }
  }
</script>

<style lang="scss" scoped>
  .count {
    display: flex;
    margin-bottom: 10px;
    flex-flow: row wrap;

    p {
      // flex: 1;
      height: 35px;
      min-width: 250px;
    }
  }

  .cancellation {
    background-color: #f4f4f4;
  }
</style>
